package com.huika.dealontop.control.base.extend;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.control.base.extend.impl.IStatusPageProvider;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.UIUtils;

import java.lang.reflect.Type;

/**
 * Author: Victor Wu
 * Email: victor-wu*foxmail.com
 * Time: 2015/11/12 14:14
 * Description: 状态页
 */
public class StatusPage<T> extends FrameLayout implements Response.Listener<RequestResult<T>> {

    public static final int STATE_NONE = -1;            // 无状态
    public static final int STATE_LOADING = 0;          // 加载中的状态
    public static final int STATE_EMPTY = 1;            // 空的状态
    public static final int STATE_ERROR = 2;            // 错误的状态
    public static final int STATE_SUCCESS = 3;          // 成功的状态

    private int mCurrentState = STATE_NONE;    // 用来标记当前属于什么状态，就显示什么View

    private View mPreview;                     // 预览View
    private View mLoadingView;                  // 正在加载中的View
    private View mEmptyView;                    // 数据为空的View
    private View mErrorView;                    // 错误页面的View
    private View mSuccessView;                  // 成功的view

    private boolean loadingFloat;

    private MyFormResultRequest request;

    private Type type;
    /**
     * 页面提供者
     */
    private IStatusPageProvider<T> mPageProvider;

    /**
     * 页面数据
     */
    private T mPageResult;

//    private AnimationDrawable mLoadingAnimation;

    public StatusPage(Context context, IStatusPageProvider<T> pageProvider) {
        super(context);
        this.mPageProvider = pageProvider;
        initView();
    }

    public StatusPage(Context context, AttributeSet attrs, IStatusPageProvider<T> pageProvider) {
        super(context, attrs);
        this.mPageProvider = pageProvider;
        initView();
    }

    public IStatusPageProvider<T> getPageProvider() {
        return mPageProvider;
    }

//    public void setPageProvider(IStatusPageProvider<T> pageProvider) {
//        this.mPageProvider = pageProvider;
//    }

    public boolean isLoadingFloat() {
        return loadingFloat;
    }

    public void setLoadingFloat(boolean loadingFloat) {
        this.loadingFloat = loadingFloat;
    }

    private void initView() {

        //1.预显示页面
        if (mPreview == null) {
            // 初始化
            mPreview = onCreatePreview();
            if (mPreview != null) {
                addView(mPreview);
            }
        }

        // 2. 加载数据
        if (mLoadingView == null) {
            // 初始化
            mLoadingView = onCreateLoadingView();
            if(mLoadingView != null){
                addView(mLoadingView);
            }
        }

        // 3. 加载数据为空
        if (mEmptyView == null) {
            // 初始化
            mEmptyView = onCreateEmptyView();
            if(mEmptyView != null){
                addView(mEmptyView);
            }
        }

        // 4. 加载失败
        if (mErrorView == null) {
            // 初始化
            mErrorView = onCreateErrorView();
            if(mErrorView != null){
                addView(mErrorView);
            }

        }

        // 根据状态显示view
        safeUpdatePageStyle();
    }

    /**
     * 子线程或主线程更新界面
     */
    private void safeUpdatePageStyle() {
        UIUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updatePageStyle();
            }
        });
    }

    /**
     * 主线程更新界面
     */
    private void updatePageStyle() {

        if (mPreview != null) {
            mPreview.setVisibility(mCurrentState == STATE_NONE
                    || (mCurrentState == STATE_LOADING && loadingFloat)
                    ? View.VISIBLE : View.GONE);
        }

        // 1.loading
        if (mLoadingView != null) {
            mLoadingView.setVisibility(mCurrentState == STATE_LOADING ? View.VISIBLE : View.GONE);
//            if (mLoadingAnimation != null) {
//                if (mCurrentState == STATE_LOADING) {
//                    mLoadingAnimation.start();
//                } else {
//                    mLoadingAnimation.stop();
//                }
//            }
        }

        // 2. empty
        if (mEmptyView != null) {
            mEmptyView.setVisibility(mCurrentState == STATE_EMPTY ? View.VISIBLE : View.GONE);
        }

        // 3. error
        if (mErrorView != null) {
            mErrorView.setVisibility(mCurrentState == STATE_ERROR ? View.VISIBLE : View.GONE);
        }

        // 4. 成功页面的显示
        if (mSuccessView != null) {
            mSuccessView.setVisibility(mCurrentState == STATE_SUCCESS || //加载成功
                    (mCurrentState == STATE_LOADING && loadingFloat)  //浮动加载中
                    ? View.VISIBLE : View.GONE);
        }

        /**
         * 成功页面的获取
         */
        if (mCurrentState == STATE_SUCCESS) {
            if (mSuccessView != null) {
                // 初始化View
                removeView(mSuccessView);
                mSuccessView = null;
            }

            mSuccessView = onCreateSuccessView(mPageResult);
            if (mSuccessView != null) {
                ViewGroup parent = (ViewGroup) mSuccessView.getParent();
                if (parent != null) {
                    parent.removeView(mSuccessView);
                }
            }
            if (mPreview != null && mSuccessView == mPreview) {
                //移除相同的view对象
                removeView(mPreview);
                mPreview = null;
            }

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            // add
            addView(mSuccessView, params);
//            addView(mSuccessView);
        }

        //刷新下ui
        this.invalidate();
    }

    /**
     * 加载数据的方法
     */
    public void startLoadData() {
        if (mCurrentState == STATE_EMPTY
                || mCurrentState == STATE_ERROR
                || mCurrentState == STATE_NONE) {
            RequestProtocol requestProtocol;
            if (this.mPageProvider != null && (requestProtocol = this.mPageProvider.onLoadData()) != null) {
                //更改状态
                onLoadingPagerStateChanged(mCurrentState, STATE_LOADING);
                mCurrentState = STATE_LOADING;
                /******************************************
                 * 使用Volley异步访问网络
                 *****************************************/
                type = new MyType().getType();
                request = new MyFormResultRequest(requestProtocol.getUrl(),
                        StatusPage.this,
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                volleyError.printStackTrace();
                                onLoadingPagerStateChanged(mCurrentState, STATE_LOADING);
                                mCurrentState = STATE_ERROR;
                                safeUpdatePageStyle();
                            }
                        }, requestProtocol.getType());

                request.setRequestParams(requestProtocol);
                VolleyRequestManager.addRequest(request, this);
            }
        }
        safeUpdatePageStyle();
    }

    public class MyFormResultRequest extends FormResultRequest<T> {
        public MyFormResultRequest(String url, Response.Listener listener, Response.ErrorListener errorListener, Type typeOfT) {
            super(url, listener, errorListener, typeOfT);
        }
    }

    public class MyType extends TypeToken<RequestResult<T>> {

    }

    /******************************************
     * Volley异步访问回调
     *****************************************/
    @Override
    public void onResponse(RequestResult<T> requestResult) {
        if (this.mPageProvider != null) {
            StatusResult statusResult = mPageProvider.onCheckResult(requestResult);
            int state = statusResult.getState();
            if (state == STATE_SUCCESS) {
                Gson gson = new Gson();
                String json = gson.toJson(requestResult.getRs());
                this.mPageResult = requestResult.getRs();
            }
            if (mCurrentState != state) {
                onLoadingPagerStateChanged(mCurrentState, state);
            }
            mCurrentState = state;
            // UI改变
            safeUpdatePageStyle();
        }
    }

    public void cancelRequest() {
        VolleyRequestManager.cancelAll(this);
    }

    /**
     * 重新加载数据
     */
    /*public void reLoadData(boolean isQuiet) {
        if (!isQuiet) {
            //显示加载页面的加载
            mCurrentState = STATE_NONE;
            startLoadData();
        } else {
            //静默的重新刷新
            if (mCurrentState != STATE_SUCCESS) {
                //之前没有成功加载过数据
                startLoadData();
            } else {
                //ThreadManager.getLongRunPool().execute(new LoadDataTask());
            }
        }
    }*/

    /*public void reLoadData() {
        reLoadData(true);
    }*/
    private View onCreatePreview() {
        View preview = null;
        if (this.mPageProvider != null) {
            preview = this.mPageProvider.onCreatePreview();
        }
        return preview;
    }

    private View onCreateSuccessView(T t) {
        View successView = null;
        if (this.mPageProvider != null) {
            successView = this.mPageProvider.onCreateSuccessView(t);
        }
        return successView;
    }

    /**
     * 获取加载页面
     *
     * @return
     */
    protected View onCreateLoadingView() {
        View loadingView = null;
        if (this.mPageProvider != null) {
            loadingView = this.mPageProvider.onCreateLoadingView();
        }
        return loadingView;
    }

    /**
     * 获取错误页面
     *
     * @return
     */
    protected View onCreateErrorView() {
        View errorView = null;
        if (this.mPageProvider != null) {
            errorView = mPageProvider.onCreateErrorView();
        }
        return errorView;
    }

    /**
     * 获取空页面
     *
     * @return
     */
    protected View onCreateEmptyView() {
        View emptyView = null;
        if (this.mPageProvider != null) {
            emptyView = mPageProvider.onCreateEmptyView();
        }
        return emptyView;
    }

    /*class LoadDataTask implements Runnable {

        @Override
        public void run() {
            // 获取数据
            StatusResult result = onStartLoadData();

            // 根据结果得到状态值
            final int state = result.getState();
            if (mCurrentState != state) {
                UIUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onLoadingPagerStateChanged(mCurrentState, state);
                    }
                });
            }
            mCurrentState = state;
            // UI改变
            safeUpdatePageStyle();
        }
    }*/

    /**
     * 当转态给改变
     */
    protected void onLoadingPagerStateChanged(int oldState, int newState) {
        if (mPageProvider != null)
            mPageProvider.onPagerStateChanged(oldState, newState);
    }

    public enum StatusResult {
        EMPTY(STATE_EMPTY), ERROR(STATE_ERROR), SUCCESS(STATE_SUCCESS);

        int state;

        private StatusResult(int state) {
            this.state = state;
        }

        public int getState() {
            return state;
        }
    }
}
